package com.aijk.web.admin.controller.sys;

import com.aijk.base.entity.SysFlag;
import com.aijk.commons.exception.ErrorCodeException;
import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.PasswordHelper;
import com.aijk.commons.utils.Utils;
import com.aijk.commons.web.constant.DubboVersionSystemConstant;

import com.aijk.ehm.sys.api.SysAdminApi;
import com.aijk.ehm.sys.api.SysAdminRoleApi;
import com.aijk.ehm.sys.api.SysRoleApi;
import com.aijk.ehm.sys.model.SysAdmin;
import com.aijk.ehm.sys.model.SysAdminRole;
import com.aijk.ehm.sys.model.SysRole;
import com.aijk.ehm.sys.model.qo.AdminRoleQo;
import com.aijk.ehm.sys.model.qo.SysAdminQo;
import com.aijk.ehm.sys.model.qo.SysRoleQo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.Constant;
import com.aijk.web.admin.model.SysAdminExt;
import com.aijk.web.admin.utils.CompanyUtil;
import com.aijk.web.admin.utils.DataTableUtil;
import com.aijk.web.admin.utils.RandomString;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping(value = "/admin/sys/admin")
public class SysAdminController extends BaseController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ADMIN_API)
	private SysAdminApi adminApi;

	@Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ROLE_API)
	private SysRoleApi roleApi;

	@Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ADMIN_ROLE_API)
	private SysAdminRoleApi adminRoleApi;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@RequiresPermissions("admin:sys:admin:list")
	public String list_view(Model model) {
		SysRoleQo roleQo = CompanyUtil.addAuth(getCurrentUser(),SysRoleQo.class);
		List<SysRole> roles = roleApi.getList(roleQo);
		model.addAttribute("roles",roles);
		return "sys/admin_list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@RequiresPermissions("admin:sys:admin:list")
	@ResponseBody
	public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
		Long iTotalRecords;
		DataTableUtil.FormatOptions(skey);
		CompanyUtil.addAuth(skey,getCurrentUser());
		SysAdminQo qo = DataTableUtil.fillQo(skey,SysAdminQo.class);
		draw += 1;

		if(Utils.hasKeyNotEmpty(skey,"role")){//查询角色 ---策划有病！^v^
			AdminRoleQo adminRoleQo = new AdminRoleQo();
			adminRoleQo.setRoleId(Utils.toInteger(skey.get("role")));
			List<SysAdminRole> adminRoles = adminRoleApi.getList(adminRoleQo);
			List<Integer> adminIds=new ArrayList<>();
			for(SysAdminRole adminRole:adminRoles){
				adminIds.add(adminRole.getAdminId());
			}
			if(adminIds.size()>0)
		    	qo.setAdminIdList(adminIds);
			else
				qo.setAdminType((short)-1);
		}

		PageInfo<SysAdmin> list = adminApi.getPage(qo);

		iTotalRecords =list.getTotal();
		RetMsg regMsg = new RetMsg();

		List<SysAdmin> sysAdmins = list.getList();
		List<SysAdminExt> sysAdminExts =new ArrayList<>();
		List<Integer> admin_ids =new ArrayList<>();
		for (SysAdmin admin:sysAdmins){
			admin_ids.add(admin.getAdminId());
		}
		Map<Integer,List<Integer>> adminRoleMap =new HashMap<>();
		Map<Integer,SysRole> roleMap =new HashMap<>();
		if(admin_ids.size()>0) {
			AdminRoleQo arQo = new AdminRoleQo();
			List<Integer> roleIds=new ArrayList<>();
			arQo.setInAdminIds(admin_ids);
			List<SysAdminRole> adminRoles = adminRoleApi.getList(arQo);
			for (SysAdminRole adminRole:adminRoles){
				roleIds.add(adminRole.getRoleId());
				List<Integer> tempRoles;
				if(adminRoleMap.containsKey(adminRole.getAdminId())){
					tempRoles=adminRoleMap.get(adminRole.getAdminId());
				}else{
					tempRoles=new ArrayList<>();
				}
				tempRoles.add(adminRole.getRoleId());
				adminRoleMap.put(adminRole.getAdminId(),tempRoles);
			}
			if(roleIds.size()>0) {
				SysRoleQo roleQo = new SysRoleQo();
				roleQo.setInRolesId(roleIds);
				List<SysRole> roles = roleApi.getList(roleQo);
				for(SysRole role:roles){
					roleMap.put(role.getRoleId(),role);
				}
			}
		}

		for (SysAdmin admin:sysAdmins){
			SysAdminExt ext= PojoUtil.convert(admin,SysAdminExt.class);
			if(adminRoleMap.containsKey(ext.getAdminId())){
				String str_role="";
				List<Integer> roleids= adminRoleMap.get(ext.getAdminId());
				for(Integer rid:roleids){
					if(roleMap.containsKey(rid)){
						str_role+=roleMap.get(rid).getRoleName()+",";
					}
				}
				ext.setRoles((str_role.length()>0?str_role.substring(0,str_role.length()-1):str_role));
			}
			sysAdminExts.add(ext);
		}

		regMsg.put("data",sysAdminExts);
		regMsg.put("draw", draw);
		regMsg.put("recordsTotal", iTotalRecords);
		regMsg.put("recordsFiltered", iTotalRecords);

		return regMsg;
	}
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add_view(Model model) {
		SysRoleQo qo= new SysRoleQo();
		qo.setSysFlag(Constant.SYS_PE_FLAG);
		if (isSubCompany()){
			qo.setCompanyId(getCurrentUser().getCompanyId().longValue());
		}
		List<SysRole> roles = roleApi.getList(qo);
		model.addAttribute("roles",roles);
		model.addAttribute("method","add");
		model.addAttribute("adminType",getCurrentUser().getAdminType());
		return "sys/admin_edit";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg add(@Valid SysAdmin admin, @RequestParam(value = "roles") String roles) {
		try {
			admin.setSalt(RandomString.generateRandomString(16));
			admin.setPassword(PasswordHelper.encryptPassword("123456", admin.getSalt()));
			SysAdmin custuser = adminApi.get(getShiroUser().getUserId());
			if (isSubCompany()){
				admin.setCompanyId(custuser.getCompanyId());
			}
			admin.setSysFlag(custuser.getSysFlag());
			admin.setAdminState((short)0);
			admin.setCreateTime(new Date());
			if(admin.getAdminType()==null){
				admin.setAdminType((short)2);
			}
			adminApi.save(admin,roles);
		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}

	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update_view(@RequestParam(value = "id") Integer id, Model model) {
		SysRoleQo qo= new SysRoleQo();
		qo.setSysFlag(Constant.SYS_PE_FLAG);
		if(isSubCompany()){
			qo.setCompanyId(getCurrentUser().getCompanyId().longValue());
		}
		List<SysRole> roles = roleApi.getList(qo);
		model.addAttribute("roles",roles);
		SysAdmin admin= adminApi.get(id);
		model.addAttribute("admin",admin);
		AdminRoleQo arqo=new AdminRoleQo();
		arqo.setAdminId(id);
		List<SysAdminRole> adminRoles = adminRoleApi.getList(arqo);
		String rids ="";
		for(SysAdminRole adminRole:adminRoles){
			rids+=adminRole.getRoleId()+",";
		}
		if(rids.length()>0)
		model.addAttribute("rids",rids.substring(0,rids.length()-1));
		model.addAttribute("method","update");
		model.addAttribute("adminType",getCurrentUser().getAdminType());
		return "sys/admin_edit";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg update(@Valid SysAdmin admin, @RequestParam(value = "roles") String roles) {
		try {
			adminApi.update(admin,roles);
		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}

	@RequestMapping(value = "/del", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg del(@RequestParam(value = "id") Integer id) {
		try {
			adminApi.delete(id);
		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}
	@RequestMapping(value = "/forbid", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg forbid(@RequestParam(value = "id") Integer id, @RequestParam(value = "status") Short status) {
		try {
			if(status==1&&getCurrentUser().getAdminId()==id){
				return RetMsg.failed("不能注销当前用户!");
			}
			SysAdmin admin =new SysAdmin();
			admin.setAdminId(id);
			admin.setAdminState(status);

			adminApi.update(admin);
		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public String detail_view(@RequestParam(value = "id") Integer id, Model model) {

		SysAdmin admin= adminApi.get(id);
		model.addAttribute("admin",admin);
		AdminRoleQo arqo=new AdminRoleQo();
		arqo.setAdminId(id);
		List<SysAdminRole> adminRoles = adminRoleApi.getList(arqo);
		List<Integer> rids =new ArrayList<>();
		for(SysAdminRole adminRole:adminRoles){
			rids.add(adminRole.getRoleId());
		}
		if(rids.size()>0){
			SysRoleQo qo= new SysRoleQo();
			qo.setInRolesId(rids);
			List<SysRole> roles = roleApi.getList(qo);
			model.addAttribute("roles",roles);
		}
		return "sys/admin_detail";
	}

	@RequestMapping(value = "/existed", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg existed(@Valid SysAdmin admin) {
		try {
			SysAdminQo qo = new SysAdminQo();
			if(Utils.isNotEmpty(admin.getAdminId())){
				qo.setAdminIdNotEqual(admin.getAdminId());
			}
			if(Utils.isNotEmpty(admin.getUsername())){
				qo.setUsername(admin.getUsername());
				List<SysAdmin> admins = adminApi.get(qo);
				if(admins.size()>0) return RetMsg.failed();
			}

		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}

	@RequestMapping(value = "/resetPass", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg resetPass(@RequestParam(value = "adminId") Integer adminId) {
		try {
			SysAdmin admin =new SysAdmin();
			admin.setAdminId(adminId);
			admin.setSalt(RandomString.generateRandomString(16));
			admin.setPassword(PasswordHelper.encryptPassword("123456", admin.getSalt()));
			adminApi.update(admin);
		}catch (ErrorCodeException e){
			e.printStackTrace();
			return RetMsg.failed();
		}
		return RetMsg.success();
	}

	@RequestMapping(value = "/editpsd", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg editpsd(@RequestParam(value = "password_old") String password_old, @RequestParam(value = "password") String password) {
		SysAdminQo adminQo =new SysAdminQo();
		adminQo.setUsername(getCurrentUser().getUsername());
		List<SysAdmin> sysAdmins = adminApi.get(adminQo);
		if(sysAdmins.size()>0){
			SysAdmin admin =sysAdmins.get(0);
			if(!PasswordHelper.encryptPassword(password_old, admin.getSalt()).equals(admin.getPassword())){
				return RetMsg.failed("原密码错误!");
			}
			admin.setPassword(PasswordHelper.encryptPassword(password, admin.getSalt()));
			if(adminApi.update(admin)>0){
				return RetMsg.success();
			}
		}
		return  RetMsg.failed();
	}
	@RequestMapping(value = "/editpsd", method = RequestMethod.GET)
	public String editpsd_view(Model model) {
		return "sys/admin_psd_edit";
	}
}

